// pages/idleReleaseSub/idleReleaseSub.js
import { shareOptions } from "../../utils/access";
import { parse } from "../../utils/utils"
import request from "../../utils/request";
const api = require("../../config/api");

Page({

  /**
   * 页面的初始数据
   */
  data: {
      tagList:[
        // { name: "免费", id: 1, checked: false },
        { name: "捡漏", id: 2, checked: false },
        { name: "9成新", id: 3, checked: false },
        { name: "功能完美", id: 4, checked: false }
      ], //标签列表
      isTagEdit: false, //标签编辑
      showTagAdd: false, //展示标签添加输入框
      tagAddFocus: false, //标签添加输入框获取焦点
      goodsDesc: '', //描述
      contactWay: false, //联系方式

      prevParams: {}, //上一页数据
      goodsId: '', //商品id
      draftId: '' //草稿id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      let tagList= this.data.tagList
      // 编辑，标签不使用系统数据
      if(options.goodsId && options.goodsId!=='undefined'){
        if(options.tagList && options.tagList!=='null'){
          tagList= parse(options.tagList)
        }else{
          tagList=[]
        }
      }else{
        if(options.tagList && options.tagList!=='null'){
          tagList=[...parse(options.tagList), ...tagList]
        }
      }
      this.setData({
         prevParams: parse(options.params),
         tagList,
         draftId: options.draftId || '',
         goodsId: options.goodsId || ''
      })
      if(this.data.goodsId && this.data.goodsId!=='undefined'){
        this.getGoodsDetail(this.data.goodsId)
      }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  // 标签选择
  tagSelect(e){
    let index= e.currentTarget.dataset.index
    this.setData({
      [`tagList[${index}].checked`]: !this.data.tagList[index].checked
    })
  },
  // 标签编辑
  tagEdit(){
   this.setData({
      isTagEdit: !this.data.isTagEdit,
      showTagAdd: false
  })
  },
  // 删除标签
  tagDelClick(e){
    let index= e.currentTarget.dataset.index
    let tagList= this.data.tagList
    tagList.splice( index, 1 )
    this.setData({
      tagList
    })
  },
  // 添加标签
  tagAddClick(){
    if(this.data.tagList.length >= 10){
      wx.showToast({
        title: '最多十个标签',
        icon: 'none'
      })
      return 
    }
    this.setData({
      showTagAdd: true,
      tagAddFocus: true
    })
  },
  // 标签确定
  tagAddBlur(e){
    if(this.loading) return
    this.loading= true
    let tagList= this.data.tagList
    let val= e.detail.value
    let reg= /[^A-Za-z0-9\u4e00-\u9fa5]+/;
    if(val===''){
      wx.showToast({
        title: '标签不能为空',
        icon: 'none'
      })
      this.loading= false
      return 
    }else if(reg.test(val)){
      wx.showToast({
        title: '只能输入汉字、英文、字母',
        icon: 'none'
      })
      this.loading= false
      return 
    }
    tagList.push({
      name: val,
      checked: true
    })
    this.setData({
      tagList,
      showTagAdd: false
   })
   this.loading= false
  },
  // 详细信息输入
	bindKeyTextarea(e) {
		if (e.detail.value.length > 120) {
			wx.showToast({
				title: "最多输入120字符",
				icon: "none",
				duration: 2000,
			});
			this.setData({
				goodsDesc: e.detail.value.slice(0, 120),
			});
		} else {
			this.setData({
				goodsDesc: e.detail.value
			});
		}
  },
  // 联系方式选择
  contactWaySelect(){
     this.setData({
       contactWay: !this.data.contactWay
     })
  },
  // 获取商品数据
	async getGoodsDetail(goodsId) {
		const { tagList } = this.data
		const res = await request.get(
			api.goodsDetail,
			{ id: goodsId },
			{ loading: false }
		);
    // 回显多选标签
    let goodsSigns= res?.data?.goodsSigns || []
    if (goodsSigns.length > 0) {
     tagList.forEach(item=>{
        let index = goodsSigns.findIndex(subItem => subItem === item.name)
        if(index!==-1){
          goodsSigns.splice(index,1)
        }
     })
   }
    goodsSigns.forEach(item=>{
      tagList.push({name: item, checked: true})
    })
		this.setData({
      tagList,
      goodsDesc: res?.data?.goodsDesc,
      contactWay: res?.data?.buyerCallStatus===1? true : false
    })
  },
  // 保存
  async handleRelease(e){
    let type= e.currentTarget.dataset.type
    let {
			ossImageList,
			goodsPrice,
			communityId,
			selectCommunityId,
			goodsClassifyId,
			goodsSubClassifyId,
    } = this.data.prevParams;
    let { goodsDesc, tagList, contactWay, goodsId, draftId}= this.data
    let goodsSigns= []
    tagList.forEach(item=>{
      if(item.checked){
        goodsSigns.push(item.name)
      } 
    })
    wx.showLoading({
			title: "商品信息校验中",
			icon: "loading",
			duration: 10000,
			mask: true,
    });
    
    let params={
      urls: ossImageList,
      goodsPrice: goodsPrice,
      communityId: selectCommunityId || communityId,
      goodsDesc,
      goodsClassifyId: goodsClassifyId || "",
      goodsSubClassifyId: goodsSubClassifyId,
      goodsSigns,
      buyerCallStatus: contactWay? 1 : 0
    }
    let url= type=='edit'? api.goodsEdit : api.goodsPublish
    // 编辑
    if(this.data.goodsId && this.data.goodsId!=='undefined'){
      params.id= goodsId
    }
		const res = await request.post(
			url,
			params,
			{
				loading: false,
			}
		);
		if (res?.httpStatus == 200) {
      wx.setStorageSync('hideDraftModal', true)
      // 如果有草稿，删除草稿
      if(draftId && draftId!=='undefined'){
        await request.post(api.deleteTempGoods,{ id: draftId },{ loading: false })
      }
      wx.hideLoading();
      var pages = getCurrentPages(); //当前页面
			var beforePage = pages[pages.length - 3]; //前二页
			beforePage.onLoad(); // 执行前二个页面的onLoad方法
			wx.navigateBack({
				delta: 2,
      });
		} else {
			wx.hideLoading();
			wx.showToast({
				title: res.msg,
				icon: "none",
				duration: 2000,
			});
		}
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    return shareOptions('default', e)
  }
})